<!-- 用户管理 -->
<template>
  <div id="user-profile" class="app-container">
    <el-tabs v-model="activeName" class="common-tabs">
      <el-tab-pane label="基本资料" name="base" />
      <el-tab-pane label="详情资料" name="details" />
      <el-tab-pane label="用户权限" name="permission" />
    </el-tabs>
    <div style="overflow: auto;" class="p-t-10">
      <el-form ref="dataForm" :rules="rules" :model="userRecord" label-position="right" label-width="120px" style="max-width: 21cm;">
        <template v-if="activeName==='base'">
          <el-form-item label="授权角色:">
            <el-tag v-for="item in userRecord.upmsRoles" :key="item.id" style="margin-right:10px">{{ item.name }}</el-tag>
          </el-form-item>
          <el-form-item label="隶属单位:">
            <span v-for="item in userRecord.upmsOrganizations" :key="item.id">
              <el-tag v-if="item.type===1" style="margin-right:10px" :type="item.id===userInfo.cacheOrganizationVo.id?'danger':''">
                {{ item.organizationName }}
              </el-tag>
            </span>
            <span v-if="userRecord.upmsOrganizations.length===0" class="color-danger  common-cursor"> 还未加入任何组织 </span>
          </el-form-item>
          <el-form-item label="隶属部门:">
            <span v-for="item in userRecord.upmsOrganizations" :key="item.id">
              <el-tag v-if="item.type===2" style="margin-right:10px">{{ item.organizationName }}</el-tag>
            </span>
          </el-form-item>
          <el-form-item label="员工编号:">{{ userRecord.userCode }} </el-form-item>
          <el-form-item label="用户名:">{{ userRecord.userName }}
            <span v-if="!userRecord.userName">
              <i class="el-icon-edit color-primary  common-cursor" @click="handleSetUserName" />
            </span>
            <span v-if="userRecord.userName ===userRecord.mobile">
              <i class="el-icon-edit color-primary  common-cursor" @click="handleSetUserName" />
            </span>
            <span v-if="userRecord.isInner===1" style="margin-left:8px" class="color-primary">内部员工</span>
            <span v-if="userRecord.isInner===0" style="margin-left:8px" class="color-danger">外部员工</span>
          </el-form-item>
          <el-form-item label="姓名:" prop="realName">
            <el-input v-model="userRecord.realName" maxlength="10" show-word-limit placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号:">{{ userRecord.mobile }}</el-form-item>

          <el-form-item label="性别:" prop="gender">
            <el-radio-group v-model="userRecord.gender">
              <el-radio :label="0">保密</el-radio>
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="电子邮箱:">
            {{ userRecord.email }}
            <span v-if="!userRecord.email">还未绑定邮箱，<span class="color-danger common-cursor" @click="handleBindEmail">去绑定</span></span>
          </el-form-item>
          <el-form-item label="备注:" prop="projectDesc">
            <el-input v-model="userRecord.remarks" :rows="4" type="textarea" maxlength="200" show-word-limit placeholder="请输入备注" />
          </el-form-item>
          <el-form-item label="注册时间:">
            {{ userRecord.gmtCreated | formatDate }}
          </el-form-item>
          <el-row>
            <el-col :span="24" class="tc">
              <el-button type="primary" plain @click="updateData">修改</el-button>
            </el-col>
          </el-row>
        </template>
        <div v-show="activeName==='permission'">
          <el-form-item label="授权权限：">
            <div>共<span class="color-danger" style="margin:0 3px">{{ defaultCheckedKeys.length }}</span>个权限</div>
            <div style="overflow: auto;">
              <el-tree
                ref="menuTree"
                class="common-el-tree"
                :data="permissionData"
                show-checkbox
                :check-strictly="false"
                node-key="id"
                :default-expand-all="true"
                :default-checked-keys="[]"
                :expand-on-click-node="false"
                :props="{children: 'permissionVos',label: 'name'}">
                <span slot-scope="{ node }" class="custom-tree-node">
                  <span class="text">
                    {{ node.label }}&nbsp;
                    <span class="color-primary">&nbsp;({{ node.data.permissionValue }})</span>
                  </span>

                </span>
              </el-tree>
            </div>
          </el-form-item>
        </div>
        <template v-if="activeName==='details'">
          <el-form-item label="姓名:">{{ userRecord.realName }}</el-form-item>
          <el-form-item label="手机号:">{{ userRecord.mobile }}</el-form-item>
          <el-form-item label="电子邮箱:">{{ userRecord.email }} </el-form-item>
          <el-form-item label="授权码:"> {{ userRecord.authorizationCode }} </el-form-item>
          <el-form-item label="用户类别:"> {{ userRecord.category | dictFormat }}</el-form-item>
          <el-form-item label="直属主管:" prop="reportsTo">{{ userRecord.reportsTo | userSelectorFormat }}</el-form-item>
          <el-form-item label="加入的组织:" prop="reportsTo">
            <el-table
              :data="userRecord.upmsOrganizations "
              style="width: 100%">
              <el-table-column prop="addTime" width="130" label="加入时间">
                <template slot-scope="scope">{{ scope.row.addTime | formatDate }}</template>
              </el-table-column>
              <el-table-column prop="type" label="标签" width="60">
                <template slot-scope="scope">
                  <el-link v-if="scope.row.type==1" class="color-primary " :underline="false">机构</el-link>
                  <el-link v-if="scope.row.type==2" class="color-danger" :underline="false">部门</el-link>
                </template>
              </el-table-column>
              <el-table-column prop="organizationName" label="组织" :show-overflow-tooltip="true" min-width="180" />
              <el-table-column label="职务" prop="orgJob" width="100" :show-overflow-tooltip="true">
                <template slot-scope="scope">{{ scope.row.orgJob?(scope.row.orgJob.split(":")[1]):'' }}</template>
              </el-table-column>
              <el-table-column prop="orgPhone" :show-overflow-tooltip="true" width="160" label="电话" />
              <el-table-column label="操作" align="center" fixed="right" width="60">
                <template slot-scope="scope">
                  <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdateUser(scope.row)" />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-row>
            <el-col :span="12">
              <el-form-item label="民族:" prop="nation">
                <data-dict-select v-model="userRecord.nation" :code="'nation'" placeholder="请选择民族" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="籍贯:" prop="nativePlaces">
                <region-selector ref="regionSelect" v-model="userRecord.nativePlace" :hide-street="true" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="入职时间:" prop="startWorkDate">
                <el-date-picker
                  v-model="userRecord.startWorkDate"
                  style="width:100%"
                  type="date"
                  value-format="timestamp"
                  placeholder="选择入职时间" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="证件号码:" prop="idNumber">
                <el-input v-model="userRecord.idNumber" maxlength="18" show-word-limit placeholder="请输入证据按号码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="政治面貌:" prop="politicalOutlook">
                <data-dict-select v-model="userRecord.politicalOutlook" :code="'political'" placeholder="请选择政治面貌" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文化程度:" prop="educationDegree">
                <data-dict-select v-model="userRecord.educationDegree" :code="'educatio'" placeholder="请选择文化程度" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="婚姻状况:" prop="maritalStatus">
                <data-dict-select v-model="userRecord.maritalStatus" :code="'marital'" placeholder="请选择婚姻状况" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所学专业:" prop="major">
                <data-dict-select v-model="userRecord.major" :code="'major'" placeholder="请选择所需专业" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="毕业院校:" prop="graduateSchool">
                <el-input v-model="userRecord.graduateSchool" maxlength="20" show-word-limit placeholder="请输入毕业院校" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最高学位:" prop="highestDegree">
                <el-input v-model="userRecord.highestDegree" maxlength="18" show-word-limit placeholder="请输入最高学位" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="学历:" prop="education">
                <data-dict-select v-model="userRecord.education" :code="'education'" placeholder="请选择学历" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="微信:" prop="weixin">
                <el-input v-model="userRecord.weixin" maxlength="25" show-word-limit placeholder="请输入微信" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="出生年月:" prop="birthday">
                <el-date-picker
                  v-model="userRecord.birthday"
                  style="width:100%"
                  type="date"
                  value-format="timestamp"
                  placeholder="选择入出生年月" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="办公电话:" prop="phone">
                <el-input v-model="userRecord.phone" maxlength="11" show-word-limit placeholder="请输入办公电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="紧急联系:" prop="emergencyContact">
                <el-input v-model="userRecord.emergencyContact" maxlength="11" show-word-limit placeholder="请输入紧急联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急电话:" prop="emergencyContactMobile">
                <el-input v-model="userRecord.emergencyContactMobile" maxlength="11" show-word-limit placeholder="请输入紧急联系电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="现住址:" prop="currentResidence">
            <region-selector ref="regionSelect" v-model="userRecord.currentResidence" />
          </el-form-item>
          <el-form-item label="详细地址:" prop="currentAddress">
            <el-input v-model="userRecord.currentAddress" maxlength="100" show-word-limit placeholder="请输入详细地址" />
          </el-form-item>
          <el-row>
            <el-col :span="24" class="tc">
              <el-button type="primary" plain @click="updateData">修改</el-button>
            </el-col>
          </el-row>
        </template>

      </el-form>
    </div>
    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :model="upmsUserOrganizationRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="电话:" prop="phone">
            <el-input v-model="upmsUserOrganizationRecord.phone" maxlength="20" show-word-limit placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="岗位:" prop="job">
            <el-select v-model="upmsUserOrganizationRecord.job" filterable placeholder="请选择岗位" style="width:100%">
              <el-option
                v-for="item in posts"
                :key="item.value"
                :label="item.name+'('+item.code+')'"
                :value="item.code+':'+item.name">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排序:" prop="orders">
            <el-input-number v-model="upmsUserOrganizationRecord.orders" placeholder="请输入排序" show-word-limit :min="1" :max="99" style="width:100%" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="updateOrgUserData">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
export default {
  components: {
  },
  data() {
    return {
      activeName: 'base',
      defaultUserProps: {
        children: 'children',
        label: 'label'
      },
      userListData: [],
      treeLoading: false,
      userId: '',
      userRecord: {
        permission: [],
        upmsOrganizations: [],
        upmsRoles: []
      },
      rules: {
        authorizationCode: [
          { required: true, message: '请输入授权码', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { validator: this.commonValidate.validateRealName, trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择用户类别', trigger: 'blur' }
        ],
        email: [
          { validator: this.commonValidate.validateEmail, trigger: 'blur' }
        ],
        userCode: [
          { required: true, message: '请输入员工编号', trigger: 'blur' },
          { min: 7, max: 7, message: '必须是7个数字', trigger: 'blur' },
          { validator: this.commonValidate.validateNumber, trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        job: [
          { required: true, message: '请选择职务', trigger: 'blur' }
        ],

        isInner: [
          { required: true, message: '请选择是否内部员工', trigger: 'blur' }
        ],
        idNumber: [
          { validator: this.commonValidate.validateIDCard, trigger: 'blur' }
        ]
      },
      permissionData: [],
      defaultCheckedKeys: [],
      posts: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: ''
      },
      upmsUserOrganizationRecord: {}
    }
  },
  computed: {
  },
  watch: {
    activeName(val) {
    },
    'userRecord.idNumber': function(val) {
      console.log(val)
      if (val) {
        var res = this.common.analyzeIDCard(val)
        if (res) {
          this.userRecord = {
            ...this.userRecord,
            gender: res.sex,
            birthday: res.birthday
          }
        } else {
          this.userRecord = {
            ...this.userRecord,
            gender: 1,
            birthday: null
          }
        }
      }
    }
  },
  created() {
    this.initUserInfo()
  },
  methods: {
    handleBindEmail() {
      window.open(this.$router.resolve({ path: '/common/personalData', query: { view: 'email' }}).href, '_self')
      window.location.reload()
    },
    async initUserInfo() {
      const res = await this.$store.dispatch('getCurrentUserDetailedInfo')

      this.userRecord = {
        ...res
      }
      const region = res.nativePlace
      this.userRecord.nativePlaces = this.common.regionFormat(region)
      this.fetchPermissionuTreeTable(res.id)
    },
    async fetchPermissionuTreeTable(userId) {
      const permissions = await this.$store.dispatch('permissionTreeTable', { 'sort': '+orders' })
      this.permissionData = permissions
      this.setDisabled(this.permissionData)
      const response = await this.$store.dispatch('getPermissionByUserId', userId)
      this.defaultCheckedKeys = []
      response.forEach(item => {
        this.defaultCheckedKeys.push(item.id)
      })
      this.$nextTick(() => {
        this.$refs.menuTree.setCheckedKeys(this.defaultCheckedKeys)
      })
    },
    setDisabled(treeData) {
      treeData.forEach((item) => {
        this.$set(item, 'disabled', true)
        if (item.permissionVos) {
          this.setDisabled(item.permissionVos)
        }
      })
    },
    updateData() {
      var tempData = Object.assign({}, this.userRecord)
      delete tempData.upmsOrganizations
      delete tempData.upmsRoles

      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('userUpdate', tempData).then(response => {
            this.msgSuccess('修改成功')
            this.initUserInfo()
          }).catch(() => {
          })
        } else {
          this.msgWarning('还有未填的参数!')
        }
      })
    },
    // 获取岗位
    fetchPostList() {
      this.$store.dispatch('postList').then((res) => {
        this.posts = res
      }).catch((_) => {
      })
    },
    handleUpdateUser(row) {
      this.fetchPostList()
      this.upmsUserOrganizationRecord = {
        id: row.userOrgId,
        type: row.type,
        orders: row.orgOrders,
        organizationId: row.id,
        fullOrganizationId: row.fullOrganizationId,
        phone: row.orgPhone,
        job: row.orgJob,
        userId: this.userRecord.id
      }
      this.sideBox = {
        recordShow: true,
        title: '编辑组织用户'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateOrgUserData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('organizationUserUpdate', this.upmsUserOrganizationRecord).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('修改成功')
            this.initUserInfo()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /**
     * 选择地区
     */
    handleRegionSelect() {
      const region = this.common.regionIdFormat(this.userRecord.nativePlace)
      const regionInfo = {
        provinceId: region.province === undefined ? '0' : region.province * 1,
        cityId: region.city === undefined ? '0' : region.city * 1,
        areaId: region.area === undefined ? '0' : region.area * 1,
        streetId: region.street === undefined ? '0' : region.street * 1
      }
      this.$refs['regionSelect'].init(regionInfo)
    },
    // 获取地址选择器的选中地址
    getRegionSelectedInfo(data) {
      this.userRecord.nativePlaces = data.selectedRegion
      this.userRecord.nativePlace = data.selectedRegionInfo1
      this.$forceUpdate()
    },
    handleSetUserName() {
      this.$prompt('请输入用户名:', '用户信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[0-9a-zA-Z].{2,10}$/,
        inputErrorMessage: '请输入3-11位用户名'
      }).then(({ value }) => {
        if (value === this.userRecord.userName) {
          this.msgWarning('用户名不能与原用户名一致！')
          this.handleSetUserName()
          return
        }
        this.$store.dispatch('modifyUserName', value).then((res) => {
          this.msgSuccess('用户名修改成功，建议重新登录系统，进行数据同步！')
          this.userRecord = {
            ...this.userRecord,
            userName: value
          }
        }).catch((_) => {
          this.handleSetUserName()
        })
      }).catch(() => {
      })
    }

  }
}
</script>
<style lang="scss">
</style>
